<template>
  <div class="p-4 max-w-md mx-auto">
    <p v-if="error" class="text-red-600 whitespace-pre-wrap">{{ error }}</p>
    <p v-else-if="loading">正在交换 token...</p>
    <p v-else>登录成功，跳转中...</p>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuth } from '@/stores/useAuth';
import { parseJwt } from '@/utils/jwt';

const error = ref<string | null>(null);
const loading = ref(true);
const router = useRouter();
const auth = useAuth();

const authority = import.meta.env.VITE_API_IDENTITY as string;
const clientId = import.meta.env.VITE_CLIENT_ID as string;
const redirectUri = import.meta.env.VITE_REDIRECT_URI as string;

onMounted(async () => {
  try {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    const state = params.get('state');

    if (!code || !state) throw new Error('缺少 code 或 state');

    const savedState = sessionStorage.getItem('pkce_state');
    if (state !== savedState) throw new Error(`state 不匹配: url=${state} stored=${savedState}`);

    const codeVerifier = sessionStorage.getItem('pkce_verifier');
    if (!codeVerifier) throw new Error('缺少 code_verifier');
    console.log(code);
    const body = new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: redirectUri,
      client_id: clientId,
      code_verifier: codeVerifier,
    });

    const resp = await fetch(`${authority}/connect/token`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: body.toString(),
    });

    const data = await resp.json();
    if (!resp.ok) {
      console.error('token 交换失败原始返回：', data);
      throw new Error(data.error_description || data.error || '换 token 失败');
    }
    console.log(data);
    console.log(parseJwt(data.access_token));
    console.log("token:" + data.access_token);


    auth.setTokens(data.access_token, data.refresh_token || undefined);
    // 清除临时
    sessionStorage.removeItem('pkce_state');
    sessionStorage.removeItem('pkce_verifier');
    localStorage.setItem('token', data.access_token); // <-- 关键

    router.replace({ name: 'Main' }); // 默认跳 MainLayout

  } catch (e: any) {
    console.error(e);
    error.value = e.message || '未知错误';
  } finally {
    loading.value = false;
  }
});
</script>
